package task

import (
	"fmt"
	"github.com/robfig/cron"
	"go.mongodb.org/mongo-driver/bson"
	"higame/config"
	"higame/modules/db"
	"higame/modules/fs"
	"higame/modules/log"
	"higame/modules/schema"
	"higame/modules/utils"
	"higame/routes/integral"
	"higame/routes/user"
	"os"
	"os/exec"
	"path"
	"strings"
)

var db = mongodb.GetInstance()
var jop *cron.Cron

func BackupDB() {
	// 备份配置数据初始化
	dbName := config.Db.DbName
	backupPath := config.Db.BackupPath()
	backupEmail := config.Db.BackupEmail
	backupTime := "01:00"
	setF := db.FindOne(config.Db.Collection.Set, bson.M{})

	set := schema.NewSet(setF).Parse()
	if set.Set.BackupTime != "" && set.Set.Addressee != "" {
		backupPath = set.Set.BackupPath
		backupEmail = set.Set.Addressee
		backupTime = set.Set.BackupTime
	}

	// 开始备份任务
	if jop != nil {
		jop.Stop()
	}
	jop = cron.New()
	timeArr := strings.Split(backupTime, ":")
	var hour int32
	var minute int32
	if len(timeArr) == 2 {
		hour = utils.StringToInt32(timeArr[0], 1)
		minute = utils.StringToInt32(timeArr[1], 0)
	}
	spec := utils.JoinString("%v %v %v %v %v %v", "0", minute, hour, "*", "*", "*", )

	_ = jop.AddFunc(spec, func() {
		dirName := utils.JoinString("%v%v", dbName, utils.Timestamp())
		outPath := path.Join(backupPath, dirName)
		// 执行sell命令来备份数据库
		cmd := exec.Command("mongodump", "-h", "127.0.0.1:27017", "-d", dbName, "-o", outPath)
		_, err := cmd.Output()
		// time.Sleep(5000)
		if err == nil {
			// 压缩数据库目录
			destFilePath := path.Join(backupPath, dirName+".tar.gz")
			err = fs.Compress(outPath, destFilePath)
			// time.Sleep(5000)
			if err == nil && fs.PathExists(destFilePath) {
				// 发送数据库文件到邮箱备份
				err = utils.SendMail(backupEmail, "数据库存档："+dirName, "数据库存档："+dirName, destFilePath)
				// time.Sleep(5000)
				if err == nil {
					// 删除本地数据库目录
					err = os.RemoveAll(outPath)
					if err != nil {
						log.Error.Println("删除数据库失败：", err)
					}
				} else {
					log.Error.Println("发送数据库失败：", err)
				}
			} else {
				log.Error.Println("压缩数据库失败：", err)
			}
		} else {
			log.Error.Println("备份数据库失败：", err)
		}
	})
	jop.Start()
}

func DbInit() {
	err := user.AddOrResetAdmin()

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("数据库操作：管理员账户与密码已经被重置\n账户：%v\n密码：%v\n", "admin", "admin")
	}

	err = integral.AddOrResetTasks()

	if err != nil {
		log.Error.Println(err)
	} else {
		fmt.Printf("数据库操作：积分任务列表已经添加或者重置\n", )
	}

	err = integral.AddOrResetPrizes()

	if err != nil {
		log.Error.Println(err)
	} else {
		fmt.Printf("数据库操作：奖品列表已经添加或者重置\n", )
	}
}
